<?php

namespace app\admin\controller;


use app\admin\model\CostBudgetDetail;
use app\admin\model\CostClassify;
use app\admin\model\CostCompany;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemQuick;
use app\common\controller\AdminController;
use think\App;
use think\facade\Env;
use app\admin\model\CostPurchaselist;
use app\admin\service\DateService;

class Index extends AdminController
{

    /**
     * 后台主页
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch('', [
            'admin' => session('admin'),
        ]);
    }


    public function getContrastData(){
        $time = $this->request->get('time');
        $type = $this->request->get('type');
        $city = $this->request->get('city',0);
        if($type == ''){
            $type = 1;
        }
        $str_time = explode(' - ',$time);
        //2021-08 - 2021-09,2021-08 - 2021-09

        if(count(array_unique($str_time)) === 1) return json(['code'=> 500,'msg' => '环比不能选择相同月份','data' => '']);
        $keys = [
            $str_time[0].'至'. $str_time[1],
            $str_time[2].'至'. $str_time[3],
        ];
        if(count(array_unique($keys)) === 1) return json(['code'=> 500,'msg' => '环比不能选择相同月份','data' => '']);
        $class_arr = CostClassify::getClass();
        if(empty($class_arr)) return json(['code' => 200, 'msg' => 'success', 'data' => []]);
        $last_time_arr = [
            1 => DateService::getDate($str_time[1])['last_day'].' 23:59:59',
            3 => DateService::getDate($str_time[3])['last_day'].' 23:59:59'
        ];
        if($type == 2) {
//            $class_arr = CostClassify::field('title,id')->where('pid',0)->select()->toArray();
//            if(empty($class_arr)) return json(['code' => 200, 'msg' => 'success', 'data' => []]);
            if($city){
                foreach ($class_arr as $key => $value) {
                    $f = CostBudgetDetail::whereIn('classify_id', $value)
                        ->where('company_id', $city)
                        ->where('time', '>=', strtotime($str_time[0]))
                        ->where('time', '<', strtotime($last_time_arr[1]))
                        ->sum('budget_price');
                    $e = CostBudgetDetail::whereIn('classify_id', $value)
                        ->where('company_id', $city)
                        ->where('time', '>=', strtotime($str_time[2]))
                        ->where('time', '<', strtotime($last_time_arr[3]))
                        ->sum('budget_price');
                    $array[] = [$f, $e];
                    $title[] = CostClassify::where('id',$key)->value('title');
                }
            }else{
                foreach ($class_arr as $key => $value) {
                    $f = CostBudgetDetail::whereIn('classify_id', $value)
                        ->where('time', '>=', strtotime($str_time[0]))
                        ->where('time', '<', strtotime($last_time_arr[1]))
                        ->sum('budget_price');
                    $e = CostBudgetDetail::whereIn('classify_id', $value)
                        ->where('time', '>=', strtotime($str_time[2]))
                        ->where('time', '<', strtotime($last_time_arr[3]))
                        ->sum('budget_price');
                    $array[] = [$f, $e];
                    $title[] = CostClassify::where('id',$key)->value('title');
                }
            }


        }else{

            if($city){
                foreach ($class_arr as $key => $value) {
                    $f = CostPurchaselist::whereIn('classify_id', $value)
                        ->where('company_id', $city)
                        ->where('time', '>=', strtotime($str_time[0]))
                        ->where('time', '<', strtotime($last_time_arr[1]))
                        ->sum('discount');
                    $e = CostPurchaselist::whereIn('classify_id', $value)
                        ->where('company_id', $city)
                        ->where('time', '>=', strtotime($str_time[2]))
                        ->where('time', '<', strtotime($last_time_arr[3]))
                        ->sum('discount');
                    $array[] = [$f, $e];
                    $title[] = CostClassify::where('id',$key)->value('title');
                }
            }else{
                foreach ($class_arr as $key => $value) {
                    $f = CostPurchaselist::whereIn('classify_id', $value)
                        ->where('time', '>=', strtotime($str_time[0]))
                        ->where('time', '<', strtotime($last_time_arr[1]))
                        ->sum('discount');
                    $e = CostPurchaselist::whereIn('classify_id', $value)
                        ->where('time', '>=', strtotime($str_time[2]))
                        ->where('time', '<', strtotime($last_time_arr[3]))
                        ->sum('discount');
                    $array[] = [$f, $e];
                    $title[] = CostClassify::where('id',$key)->value('title');
                }
            }

        }

        $series = DateService::getDataChange($array,$keys);
        foreach($series as $key => $value){
            $series_arr[] = [
                'name' => $key,
                'data' => $value
            ];
        }
        $data = [
            'time' => $keys,
            'name' => $title ?? [],
            'series_arr' => $series_arr,
        ];

        return json(['code'=> 200,'msg' => 'success','data' => $data]);

    }

    public function getClassData(){
        $time = $this->request->get('time');
        $city = $this->request->get('city',0);
        if($time == '') $time = date('Y-m',time()).' - '.date('Y-m',time());
        $str_time = explode(' - ',$time);
        $last_time = DateService::getDate($str_time[1])['last_day'].' 23:59:59';
        $class_list = CostClassify::getClass();
        if(empty($class_list)) return json(['code' => 200, 'msg' => 'success', 'data' => []]);
        if($city){
            foreach ($class_list as $key => $value){
                $budge = CostBudgetDetail::whereIn('classify_id', $value)
                    ->where('company_id', $city)
                    ->where('time', '>=', strtotime($str_time[0]))
                    ->where('time', '<', strtotime($last_time))
                    ->sum('budget_price');
                $actual = CostPurchaselist::whereIn('classify_id', $value)
                    ->where('company_id', $city)
                    ->where('time', '>=', strtotime($str_time[0]))
                    ->where('time', '<', strtotime($last_time))
                    ->sum('discount');
                $title[] = CostClassify::where('id',$key)->value('title');
                $array[] = [$budge,$actual];
            }
        }else{
            foreach ($class_list as $key => $value){
                $budge = CostBudgetDetail::whereIn('classify_id', $value)
                    ->where('time', '>=', strtotime($str_time[0]))
                    ->where('time', '<', strtotime($last_time))
                    ->sum('budget_price');
                $actual = CostPurchaselist::whereIn('classify_id', $value)
                    ->where('time', '>=', strtotime($str_time[0]))
                    ->where('time', '<', strtotime($last_time))
                    ->sum('discount');
                $title[] = CostClassify::where('id',$key)->value('title');
                $array[] = [$budge,$actual];
            }
        }

        $keys = ['预算费用','实际费用'];
        $series = DateService::getDataChange($array,$keys);

        $data = [
            'name' => $title ?? [],
            'keys' => $keys,
            'series' => $series,
        ];

        return json(['code'=> 200,'msg' => 'success','data' => $data]);

    }

    public function getClassCount(){

        $class_list = CostClassify::getClass();
        if(empty($class_list)) return json(['code' => 200, 'msg' => 'success', 'data' => []]);
        $array = [];
        foreach ($class_list as $key => $value){
            $actual = CostPurchaselist::whereIn('classify_id', $value)
                ->where('time', '>=', strtotime(date('Y-01-01')))
                ->where('time', '<', strtotime(date('Y-12-31 23:59:59')))
                ->sum('discount');
            $title = CostClassify::where('id',$key)->value('title');
            $array[] = [
                'value' => $actual,
                'name' => $title
            ];
        }
        return json(['code'=> 200,'msg' => 'success','data' => $array]);
    }

    public function getClassYear(){
        $time = $this->request->get('time',date('Y'));
        $class_id = $this->request->get('type',0);
        $class_list = CostClassify::getClass();
        if(empty($class_list)) return json(['code' => 200, 'msg' => 'success', 'data' => []]);
        $year_data = DateService::actionYear($time);
        if($class_id){
            foreach($year_data as $value){
                $actual = CostPurchaselist::whereIn('classify_id', $class_list[$class_id])
                    ->where('time', '>=', strtotime($value['first_day']))
                    ->where('time', '<', strtotime($value['last_day'].' 23:59:59'))
                    ->sum('discount');
                $keys = explode('-',$value['first_day'])[1].'月';
                $data['name'][] = $keys;
                $data['val'][] = $actual;
            }
        }else{
            foreach($year_data as $value){
                $actual = CostPurchaselist::where('time', '>=', strtotime($value['first_day']))
                    ->where('time', '<', strtotime($value['last_day'].' 23:59:59'))
                    ->sum('discount');
                $keys = explode('-',$value['first_day'])[1].'月';
                $data['name'][] = $keys;
                $data['val'][] = $actual;
            }
        }
        return json(['code'=> 200,'msg' => 'success','data' => $data]);

    }


    /**
     * 后台首页
     * @return string
     * @throws \Exception
     */
    public function welcome()
    {
        $quicks = SystemQuick::field('id,title,icon,href')
            ->where(['status' => 1])
            ->order('sort', 'desc')
            ->limit(8)
            ->select();
        $time = DateService::getDate(date('Y-m-d'));

        $budget_sum = CostBudgetDetail::where('budget_time','>=',strtotime($time['first_day']))
            ->where('budget_time','<',strtotime($time['last_day']).' 23:59:59')
            ->sum('budget_price');

        $purchase_sum = CostPurchaselist::where('time','>=',strtotime($time['first_day']))
            ->where('time','<',strtotime($time['last_day'].' 23:59:59'))
            ->sum('discount');
        $str_time = DateService::getlastMonthDays(date('Y-m-d'),false);
        $CostCompanyArr = CostCompany::field('id,company_name')->where('status',2)->select()->toArray();
        $classTop = CostClassify::field('id,title')->where('pid',0)->select()->toArray();

        $purchase_year_sum = CostPurchaselist::where('time','>=',strtotime(date('Y-01-01')))
            ->where('time','<',strtotime(date('Y-12-31 23:59:59')))
            ->sum('discount');

        $budget_year_sum = CostBudgetDetail::where('budget_time','>=',strtotime(date('Y-01-01')))
            ->where('budget_time','<',strtotime(date('Y-12-31 23:59:59')))
            ->sum('budget_price');
        $this->assign('quicks', $quicks);
        $this->assign('class_name', $classTop);
        $this->assign('time', date('Y-m',time()));
        $this->assign('class_time', $str_time[1].' - '.$str_time[1]);
        $this->assign('start_time', $str_time[0].' - '.$str_time[0]);
        $this->assign('end_time', $str_time[1].' - '.$str_time[1]);
        $this->assign('CostCompanyArr', $CostCompanyArr);
        $this->assign('year', date('Y'));
        $this->assign('sum', [
            'actual' => $purchase_sum,
            'budget' => $budget_sum,
            'year_actual' => $purchase_year_sum,
            'year_budget' => $budget_year_sum,
        ]);
        return $this->fetch();
    }

    /**
     * 修改管理员信息
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editAdmin()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        empty($row) && $this->error('用户信息不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [];
            $this->validate($post, $rule);
            try {
                $save = $row
                    ->allowField(['head_img', 'phone', 'remark', 'update_time'])
                    ->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * 修改密码
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editPassword()
    {
        $id = session('admin.id');
        $row = (new SystemAdmin())
            ->withoutField('password')
            ->find($id);
        if (!$row) {
            $this->error('用户信息不存在');
        }
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $this->isDemo && $this->error('演示环境下不允许修改');
            $rule = [
                'password|登录密码'       => 'require',
                'password_again|确认密码' => 'require',
            ];
            $this->validate($post, $rule);
            if ($post['password'] != $post['password_again']) {
                $this->error('两次密码输入不一致');
            }

            // 判断是否为演示站点
            $example = Env::get('easyadmin.example', 0);
            $example == 1 && $this->error('演示站点不允许修改密码');

            try {
                $save = $row->save([
                    'password' => password($post['password']),
                ]);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

}
